package node_battle

import (
	"reflect"
	"sanguo/cluster"
	codecs "sanguo/codec/cs"

	"github.com/golang/protobuf/proto"
	"github.com/sniperHW/kendynet"
)

type handler func(kendynet.StreamSession, *codecs.Message)
var Dispatcher dispatcher
type dispatcher struct {
	handlers map[string]handler
}

func (this *dispatcher) Register(msg proto.Message, h handler) {
	msgName := reflect.TypeOf(msg).String()
	if nil == h {
		return
	}
	_, ok := this.handlers[msgName]
	if ok {
		return
	}
	this.handlers[msgName] = h
}

func (this *dispatcher) Dispatch(session kendynet.StreamSession, msg *codecs.Message) {
	if nil != msg {
		name := msg.GetName()
		handler, ok := this.handlers[name]
		if ok {
			cluster.PostTask(func() {
				handler(session, msg)
			})
		}
	}
}

type statusHandler func(user *User)
var StatusDispatcher statusDispatcher

type statusDispatcher struct {
	handlers map[int32]statusHandler
}

func (this *statusDispatcher) Register(id int32, h statusHandler) {
	_,ok := this.handlers[id]
	if ok {
		return
	}
	this.handlers[id] = h
}

func (this *statusDispatcher) Dispatch(id int32, user *User) {
	handler, ok := this.handlers[id]
	if ok {
		handler(user)
	}else {
		panic("statusDispatcher error")
	}
}

func (this *dispatcher) OnClose(session kendynet.StreamSession, reason string) {
	Infof("client close:%s\n", reason)
}

func (this *dispatcher) OnNewClient(session kendynet.StreamSession) {
	Infof("new client\n")
}
